/**
 * Module dependencies.
 */

var express = require('express');
var http = require('http');
var wechat = require('wechat');
var API = require('wechat-api');
var config = {
    token: 'weixinServerToken',
    appid: 'wx5f22954bfd087f7c',
    secret: '8990344e5a007f9e626253be9f7f1084',
    encodingAESKey: 'hhp6uNjfYAiKHFQKPTnSf4Zaxde5YSdLPOWmzX4sy7V'
};
var OAuth = require('wechat-oauth');
var client = new OAuth(config.appid, config.secret);
var api = new API(config.appid, config.secret);
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.use(express.query());
app.use(express.static(__dirname + '/public'));
/*api.createMenu({
        "button": [{
            "type": "click",
            "name": "今日歌曲",
            "key": "V1001_TODAY_MUSIC"
        }, {
            "name": "菜单",
            "sub_button": [{
                "type": "view",
                "name": "搜索",
                "url": "http://www.soso.com/"
            }, {
                "type": "click",
                "name": "赞一下我们",
                "key": "V1001_GOOD"
            }]
        }]
    },
    function(err, result) {
        console.log(err, result);
    });*/
app.use('/img', function(req, res, next) {
    var path = req.query.path;
    if (path) {
        var opt = {};
        opt.method = "GET";
        opt.host = "cdn.91ns.com";
        opt.path = path;
        var req = http.request(opt, function(httpRes) {
            httpRes.pipe(res);
        }).on('error', function(e) {
            console.log("Got error: " + e.message);
        });
        req.end();
    } else {
        next();
    }
});
var wechatHander = wechat(config, function(req, res, next) {
    // 微信输入信息都在req.weixin上
    var message = req.weixin;
    var deal = false;
    //message.FromUserName
    switch (message.MsgType) {
        case 'event':
            //message.EventKey === ''
            if (message.Event === 'subscribe') { //进入公众号

            }
            break;
        case 'text': //文本信息
            var text = message.Content;
            var textReg = /^我是主播(\d{4,10})$/;
            var result = textReg.exec(text);
            if (result !== null) {
                httpTo({
                    path: '/users/' + result[1]
                }, function(data) {
                    data = JSON.parse(data);
                    if (data.code != 0) {
                        res.reply({
                            content: '好像哪里出问题了~~~',
                            type: 'text'
                        });
                    }
                    data = data.data;
                    var anchorData = [
                        'nickName=' + escape(data.nickName),
                        'signature=' + escape(data.signature),
                        'avatar=' + data.avatar,
                    ];
                    res.reply([{
                        title: '点我点我！获取属于你的推广二维码哦！',
                        description: '我的推广我做主~~',
                        picurl: 'http://cdn.91ns.com/web/cssimg2/logo.png',
                        url: 'http://weixin.imconfig.com/index.html?anchorUID=' + result[1] + '&' + anchorData.join('&')
                    }]);
                });
                deal = true;
            }
            break;
        case 'image': //图片信息
            //message.PicUrl//地址
            //message.MediaId//
            //
            break;
        case 'voice': //语音信息
            //message.MediaId//
            //message.Format//amr
            //message.Recognition//amr
            //
            break;
    }!deal && res.reply({
        content: '发送文字"我是主播10000"试一试吧！注：10000是主播的ID',
        type: 'text'
    });
    //回复图文
    /*res.reply([{
        title: '新鲜事',
        description: '点击查看今天的新鲜事',
        picurl: 'http://oss.imconfig.com/cn/demo/fanpaile/images/imgs.png',
        url: 'http://www.imconfig.com'
    }]);*/
    //回复音乐
    /*res.reply({
      type: "music",
      content: {
        title: "来段音乐吧",
        description: "一无所有",
        musicUrl: "http://mp3.com/xx.mp3",
        hqMusicUrl: "http://mp3.com/xx.mp3",
        thumbMediaId: "thisThumbMediaId"
      }
    });*/
    //回复文本
    /*res.reply({
      content: 'text object',
      type: 'text'
    });*/
    //回复视频
    /*res.reply({
      type: "video",
      content: {
        title: '来段视频吧',
        description: '女神与高富帅',
        mediaId: 'mediaId'
      }
    });*/
    //回复语音
    /*res.reply({
      type: "voice",
      content: {
        mediaId: 'mediaId'
      }
    });*/

});
app.use('/', wechatHander);
app.use('/wechat', wechatHander);

http.createServer(app).listen(app.get('port'), function() {
    console.log('Express server listening on port ' + app.get('port'));
});
process.on('uncaughtException', function(err) {
    console.log(err);
    console.log(err.stack);
});

function httpTo(opt, callback) {
    opt.method = opt.method || "GET";
    opt.host = opt.host || "app.91ns.com";
    opt.path = opt.path || "";
    var req = http.request(opt, function(res) {
        var body = "";
        res.on('data', function(data) {
            body += data;
        }).on('end', function() {
            callback(body);
        });
    });
    req.end();
}